package com.loren.demo03.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public class TcpSocketClientHandler extends ChannelInboundHandlerAdapter {

    private final TcpSocketClient tcpSocketClient;

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    TcpSocketClientHandler(TcpSocketClient tcpSocketClient) {
        this.tcpSocketClient = tcpSocketClient;
    }

    @Override
    public void channelActive(ChannelHandlerContext context) {
        this.checkHeartbeat(context);
    }

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) {
        String message = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
        if ("HeartbeatCheck".equals(message)) {
            context.channel().eventLoop().schedule(() -> checkHeartbeat(context), 30L, TimeUnit.SECONDS);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext context) {
        context.channel().eventLoop().execute(() -> {
            System.err.println(".......try to connect again.......");
            this.tcpSocketClient.connectNettyServer();
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
        context.close();
    }

    private void checkHeartbeat(ChannelHandlerContext context) {
        System.out.println(dateTimeFormatter.format(LocalDateTime.now()));
        context.writeAndFlush(Unpooled.copiedBuffer("HeartbeatCheck", CharsetUtil.UTF_8));
    }
}
